<template>
  <div class="card">
    <div class="card-header">
      <i class="bi bi-cloud-upload"></i> 上传 DOI
    </div>
    <div class="card-body">
      <div class="row">
        <!-- 文件上传区域 -->
        <div class="col-md-6 mb-3"> 
          <div 
            class="upload-area" 
            :class="{ 'drag-over': isDragOver }" 
            @click="triggerFileInput"
            @dragover.prevent="isDragOver = true"
            @dragleave="isDragOver = false"
            @drop.prevent="handleFileDrop"
          >
            <i class="bi bi-file-earmark-text"></i>
            <h5>拖放文件到这里或点击上传</h5>
            <p class="text-muted">支持 .txt, .xlsx, .xls 格式（txt格式的每个doi独立一行，.xlsx或.xls 格式的必须要有DOI列）</p>
            <input 
              type="file" 
              ref="fileInput" 
              accept=".txt,.xlsx,.xls" 
              style="display: none;"
              @change="handleFileChange"
            >
          </div>
        </div>
        
        <!-- 直接输入区域 -->
        <div class="col-md-6 mb-3"> 
          <div class="mb-3">
            <textarea 
              class="form-control" 
              id="doiInput" 
              v-model="doiInputText" 
              rows="6" 
              placeholder="请输入doi，多个doi请换行"
            ></textarea>
          </div>
          <div class="d-flex gap-2">
            <button 
              class="btn btn-primary" 
              @click="handleDoiInput" 
              :disabled="isSubmitting || !doiInputText.trim()"
            >
              <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
              提交 DOI
            </button>
            <button 
              class="btn btn-outline-secondary" 
              @click="clearDoiInput" 
              :disabled="isSubmitting || !doiInputText.trim()"
            >
              清空
            </button>
          </div>
        </div>
      </div>
      
      <div class="mt-3" v-if="uploadStatus">
        <div :class="`alert ${alertClass} d-flex align-items-center`" role="alert">
          <i :class="`bi ${iconClass} me-2`"></i>
          <div>{{ uploadStatus }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useTaskStore } from '@/stores/taskStore';
import { uploadDoiFile, inputDois } from '@/services/api';

const taskStore = useTaskStore();
const fileInput = ref<HTMLInputElement | null>(null);
const isDragOver = ref(false);
const uploadStatus = ref('');
const uploadStatusType = ref<'info' | 'success' | 'error' | 'loading'>('info');
const doiInputText = ref('');
const isSubmitting = ref(false);

// 计算属性
const alertClass = computed(() => {
  switch (uploadStatusType.value) {
    case 'success': return 'alert-success';
    case 'error': return 'alert-danger';
    case 'loading': return 'alert-primary';
    default: return 'alert-info';
  }
});

const iconClass = computed(() => {
  switch (uploadStatusType.value) {
    case 'success': return 'bi-check-circle';
    case 'error': return 'bi-exclamation-triangle';
    case 'loading': return 'bi-arrow-repeat';
    default: return 'bi-info-circle';
  }
});

// 方法
function triggerFileInput() {
  fileInput.value?.click();
}

function handleFileDrop(event: DragEvent) {
  isDragOver.value = false;
  const files = event.dataTransfer?.files;
  if (files && files.length > 0) {
    handleUpload(files[0]);
  }
}

function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  if (files && files.length > 0) {
    handleUpload(files[0]);
  }
}

async function handleUpload(file: File) {
  // 检查文件类型
  const fileExt = file.name.split('.').pop()?.toLowerCase();
  if (!fileExt || !['txt', 'xlsx', 'xls'].includes(fileExt)) {
    showUploadStatus('error', '不支持的文件类型，请上传 .txt, .xlsx 或 .xls 文件');
    taskStore.addNotification('error', '文件类型错误', '请上传 .txt, .xlsx 或 .xls 文件');
    return;
  }
  
  // 显示上传中状态
  showUploadStatus('loading', '正在上传文件...');
  
  try {
    // 发送上传请求
    const response = await uploadDoiFile(file);
    
    // 显示上传成功
    showUploadStatus('success', `成功解析 DOI，任务已提交`);
    
    // 添加任务到列表
    taskStore.addTask(response.data);
    
    // 显示通知
    taskStore.addNotification('success', '上传成功', `成功解析 ${response.data.total_dois} 个DOI`);
    
    // 重置文件输入
    if (fileInput.value) {
      fileInput.value.value = '';
    }
    
  } catch (error: any) {
    console.error('上传错误:', error);
    showUploadStatus('error', `上传失败: ${error.message || '未知错误'}`);
    taskStore.addNotification('error', '上传失败', error.message || '未知错误');
  }
}

async function handleDoiInput() {
  if (!doiInputText.value.trim()) {
    showUploadStatus('error', '请输入至少一个DOI');
    return;
  }
  
  isSubmitting.value = true;
  showUploadStatus('loading', '正在处理DOI...');
  
  try {
    // 发送DOI输入请求
    const response = await inputDois(doiInputText.value);
    
    // 显示成功
    showUploadStatus('success', `成功解析 ${response.data.total_dois} 个DOI，任务已提交`);
     doiInputText.value=''
    // 添加任务到列表
    taskStore.addTask(response.data);
    
    // 显示通知
    taskStore.addNotification('success', 'DOI提交成功', `成功解析 ${response.data.total_dois} 个DOI`); 
  } catch (error: any) {
    console.error('DOI提交错误:', error);
    showUploadStatus('error', `提交失败: ${error.message || '未知错误'}`);
    taskStore.addNotification('error', 'DOI提交失败', error.message || '未知错误');
  } finally {
    isSubmitting.value = false;
  }
}

function showUploadStatus(type: 'info' | 'success' | 'error' | 'loading', message: string) {
  uploadStatusType.value = type;
  uploadStatus.value = message;
  
  // 如果是成功或错误，3秒后自动清除
  if (type === 'success' || type === 'error') {
    setTimeout(() => {
      uploadStatus.value = '';
    }, 3000);
  }
}

function clearDoiInput() {
  doiInputText.value = '';
}
</script>

<style scoped>
.upload-area {
  border: 2px dashed #ccc;
  border-radius: 5px;
  padding: 1.5rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  height: auto;
  min-height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.upload-area:hover {
  border-color: #007bff;
  background-color: rgba(0, 123, 255, 0.05);
}

.upload-area.drag-over {
  border-color: #28a745;
  background-color: rgba(40, 167, 69, 0.05);
}

.upload-area i {
  font-size: 2.5rem;
  color: #6c757d;
  margin-bottom: 0.5rem;
}

@media (max-width: 767.98px) {
  .upload-area {
    min-height: 140px;
    padding: 1rem;
  }
  
  .upload-area i {
    font-size: 2rem;
    margin-bottom: 0.3rem;
  }
}
</style>